import { config } from '../config'

interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  params?: Record<string, string>
}

export class RequestError extends Error {
  constructor(public code: number, message: string) {
    super(message)
    this.name = 'RequestError'
  }
}

export const request = async <T>({
  url,
  method = 'GET',
  data,
  params
}: RequestOptions): Promise<T> => {
  const fullUrl = `${config.baseURL}/${config.apiVersion}${url}`
  
  // 处理URL参数替换
  const finalUrl = params
    ? Object.entries(params).reduce(
        (acc, [key, value]) => acc.replace(`:${key}`, value),
        fullUrl
      )
    : fullUrl

  return new Promise((resolve, reject) => {
    uni.request({
      url: finalUrl,
      method,
      data,
      timeout: config.timeout,
      success: (res: any) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(new RequestError(res.statusCode, res.data?.message || '请求失败'))
        }
      },
      fail: (err) => {
        reject(new RequestError(0, err.errMsg || '网络错误'))
      }
    })
  })
} 